import { Texture } from "three";

export default class NetUtil {
    private static getXmlHttpForTexture(url: string, texture, fn?: Function) {
        // 使用XMLHttpRequest请求图片
        let xhr = new XMLHttpRequest();
        xhr.timeout = 5000; // 5秒超时
        xhr.open('GET', url, true);
        //  xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
        xhr.responseType = 'arraybuffer';
        xhr.onloadend = function (ev: ProgressEvent) {
            // let isSuccess = (ev.loaded / ev.total) == 1;
            let isSuccess = (xhr.status >= 200 && xhr.status < 300);
            if (isSuccess) {
                // 将获取到的数据设置到纹理对象A中
                let blob = new Blob([xhr.response]);

                // 使用URL.createObjectURL创建图片URL
                let imageUrl = URL.createObjectURL(blob);
                let image = new Image();
                image.src = imageUrl;
                image.onload = function () {
                    texture.image = image;// blob; 
                    // 通过纹理对象的needsUpdate属性告知Three.js需要更新纹理
                    texture.needsUpdate = true;

                    if (fn instanceof Function) {
                        fn(true, texture);
                    }
                    NetUtil.freeImageNet(xhr, texture);
                }
            } else {
                if (fn instanceof Function) {
                    fn(false, undefined);
                }
                NetUtil.freeImageNet(xhr, texture);
            }
        }
        xhr.ontimeout = xhr.onerror = xhr.onabort = function () {
            if (fn instanceof Function) {
                fn(false, undefined);
            }
            NetUtil.freeImageNet(xhr, texture);
        }

        xhr.send();

        return xhr;
    }

    private static freeImageNet(xhr, texture) {
        xhr.abort();
        xhr.onload = null; // 解除引用
        xhr = null;
        texture['imageLoader'] = null;
    }

    /** 创建纹理 */
    public static createTexture(url: string, fn?: Function) {
        let texture = new Texture();
        let xhr = NetUtil.getXmlHttpForTexture(url, texture, fn);
        texture['imageLoader'] = xhr;
        return texture;
    }
}